import pandas as pd
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans

col_names = ['sepal-length','sepal-width','petal-length','petal-width','Species']
iris = pd.read_csv('data/Iris.csv', names=col_names,header=0) #header=None

iris.head()

#Dropping the 'Species' column
iris_clustering = iris.drop(columns =['Species'])
#Selecting 2 random features from the dataset for clustering
X = iris_clustering.iloc[:,[0,2]].values

#Using the elbow method to find the optimal number of clusters
wcss = []
for i in range(1,11):
    kmeans = KMeans(n_clusters = i, init ='k-means++', random_state = 42)
    kmeans.fit(X)
    wcss.append(kmeans.inertia_)

#plotting the elbow graph
plt.plot(range(1,11),wcss)
plt.title('The Elbow Point Graph on Iris dataset')
plt.xlabel('Number of cluster')
plt.ylabel('WCSS')
plt.show()

#Fitting K-Means to the dataset
kmeans = KMeans(n_clusters = 3, init ='k-means++', random_state=0)
#return a label for each data point based on the number of clusters
y = kmeans.fit_predict(X)
print(y)

kmeans.labels_

kmeans.inertia_   #惯性：样本到最近聚类中心的距离平方和

kmeans.n_iter_

kmeans.cluster_centers_

# Visualising the clusters
plt.scatter(X[y == 0, 0], X[y == 0, 1], s = 50, c = 'red', label = 'Cluster 1')
plt.scatter(X[y == 1, 0], X[y == 1, 1], s = 50, c = 'blue', label = 'Cluster 2')
plt.scatter(X[y == 2, 0], X[y == 2, 1], s = 50, c = 'green', label = 'Cluster 3')

plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 100, c = 'cyan', label = 'Centroids')
plt.title('Iris Flower Clusters')
plt.xlabel('Sepal Length in cm')
plt.ylabel('Petal Length in cm')
plt.legend()
plt.show()